package com.example.leetdemo.finash;

public class Solution238 {

    public int[] productExceptSelf(int[] nums) {
        if (nums.length <= 1) {
            return nums;
        }
        int[] pre = new int[nums.length];
        pre[0] = nums[0];
        int[] aft = new int[nums.length];
        aft[nums.length - 1] = nums[nums.length - 1];
        for (int i = 1; i < nums.length; i++) {
            pre[i] = nums[i] * pre[i - 1];
        }
        for (int i = nums.length - 2; i >= 0; i--) {
            aft[i] = aft[i + 1] * nums[i];
        }
        for (int i = 0; i < nums.length; i++) {
            if (i == 0) {
                nums[i] = aft[i + 1];
            } else if (i == nums.length - 1) {
                nums[i] = pre[i - 1];
            } else {
                nums[i] = aft[i + 1] * pre[i - 1];
            }
        }
        return nums;
    }
}
